import { ref, unref, computed, watch } from 'vue';

function useWithin(el, props = {}) {
	
	const isWithin = ref(false);
	
	watch(el, (newEl, oldEl, onInvalidate) => {
		if (newEl instanceof Element) {
			newEl.setAttribute('tabindex', -1);
			newEl.addEventListener('focusin', within);
			newEl.addEventListener('focusout', without);
			onInvalidate(() => {
				newEl.removeAttribute('tabindex');
				newEl.removeEventListener('focusin', within);
				newEl.removeEventListener('focusout', without);
			})
		}
	}, {
		immediate: true
	})
	
	function within(e) {
		isWithin.value = true;
		props.onWithin?.(e);
	}
	
	function without(e) {
		isWithin.value = false;
		props.onWithout?.(e);
	}
	
	return {
		isWithin
	}
	
}

export default useWithin;